package mvc.controller.app {
	import flash.display.Sprite;
	
	import mvc.model.ResourceProxy;
	import mvc.model.ViewProxy;
	import mvc.model.vo.ViewVO;
	import mvc.view.StageMediator;
	
	import org.puremvc.as3.interfaces.IMediator;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.command.SimpleCommand;

	public class AppAddViewCommand extends SimpleCommand {
		public var rscPx:ResourceProxy;
		public var vPx:ViewProxy;
		public var stageMed:StageMediator;

		public function AppAddViewCommand() {
			super();

			rscPx = facade.retrieveProxy(ResourceProxy.NAME) as ResourceProxy;
			vPx = facade.retrieveProxy(ViewProxy.NAME) as ViewProxy;

			stageMed = facade.retrieveMediator(StageMediator.NAME) as StageMediator;
		}

		public override function execute(notification:INotification):void {
			var name:String = notification.getBody() as String;
			var vo:ViewVO = vPx.getViewVO(name);
			if (rscPx.isLoaded(vo.swfPath)) {
				initView(vo);
			} else {
				rscPx.loadResource(vo.swfPath, function():void {
					initView(vo);
				});
			}
		}

		private function initView(vo:ViewVO):void {
			var component:Sprite;
			if (vo.assetClassName) {
				var asset:Class = rscPx.getResourceClass(vo.swfPath, vo.assetClassName);
				component = new asset();
			} else {
				component = rscPx.getMovieClip(vo.swfPath);
			}
			stageMed.addLayer(component, vo.name, vo.layerIndex)
			var viewComponent:Object = new vo.viewComponent(component);
			var med:IMediator = new vo.mediator(viewComponent);
		}
	}
}
